<!-- 组织-组织机构管理-组织机构图 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :breadCrumb="breadCrumb">
        <template #buts>
          <div class="hear">
            <a-button-group>
              <a-button type="outline" @click="snap">生成快照</a-button>
              <a-dropdown @select="extraClick">
                <a-button type="outline">
                  <template #icon>
                    <icon-more />
                  </template>
                </a-button>
                <template #content>
                  <a-doption :value="1">查看历史快照</a-doption>
                  <a-doption :value="2">变更历史</a-doption>
                </template>
              </a-dropdown>
            </a-button-group>
          </div>
        </template>
      </PageHeaderNew>
    </template>
    <div class="wrap">
      <nodeOrgChart
        @clickTree="clickTree"
        :data="originTreeData.data"
        :id="id"
        style="margin-right: 10px"
      ></nodeOrgChart>
      <div class="main">
        <div class="top">
          <div class="left">
            <p style="width: 90px; display: flex; align-items: center">
              显示筛选：
            </p>
            <a-select
              @change="(e)=>changeShow(e as number[])"
              :default-value="[1, 2, 3, 4, 5, 6, 7]"
              size="medium"
              :max-tag-count="3"
              multiple
              :options="controlsShow.data"
            >
            </a-select>
          </div>
          <div class="icons">
            <div class="icon">
              <a-tooltip content="按ctrl+alt+鼠标滚轮向前或键盘+号放大">
                <IconFont
                  type="icon-23fangda"
                  size="22"
                  @click="changeSize(1)"
                />
              </a-tooltip>
            </div>

            <div class="icon">
              <a-tooltip content="按ctrl+alt+鼠标滚轮向后或键盘-号缩小">
                <IconFont
                  type="icon-24suoxiao"
                  size="22"
                  @click="changeSize(2)"
                />
              </a-tooltip>
            </div>
          </div>
        </div>
        <a-divider />
        <usersChart
          @loading="getData"
          ref="chart"
          :data="clickTreeData.data || originTreeData.data"
          :style="{
            flex: 4
          }"
        ></usersChart>
      </div>
    </div>
    <snapshot v-model:visible="snapVisible" @snapshotEmit="snapshotEmit">
    </snapshot>
  </ContentCard>
</template>

<script lang="ts" setup>
import { zoomWithMouse, zoomWithPlusAndMinus } from '@/utils/utils';
import nodeOrgChart from './Components/NodesOrgChart/index.vue';
import usersChart from './Components/UsersChart/index.vue';
import snapshot from '../Structure/Components/Snapshot/index.vue';
import {
  GetOrganizationList,
  GetSnapShotList,
  PostSnap
} from '@/apis/management/organization/organizationManagement';
import { Message } from '@arco-design/web-vue';
import dayjs from 'dayjs';

const title = '组织架构图';
const router = useRouter();
const breadCrumb: string[] = ['组织', '基础设置', '组织架构图'];
const chart = ref();
const route = useRoute();
const userId = +(localStorage.getItem('userId') as string);
let id = route.query.id ? +route.query.id : 0; // 储存当前id
// watch(
//   () => route.query.id,
//   (val) => {
//     if (val && +val > 0) id.value = +val;
//     console.log(val);
//   }
// );
let snapVisible = ref(false); // 生成快照弹出框
const originTreeData = reactive<{ data: any }>({ data: {} });
const controlsShow = reactive({
  data: [
    {
      value: 1,
      label: '职位数',
      show: true
    },
    {
      value: 2,
      label: '员工数',
      show: true
    },
    {
      value: 3,
      label: '编制数',
      show: true
    },
    {
      value: 4,
      label: '负责人头像',
      show: true
    },
    {
      value: 5,
      label: '负责人职位',
      show: true
    },
    {
      value: 6,
      label: '负责人职级',
      show: true
    },
    {
      value: 7,
      label: '负责人联系方式',
      show: true
    }
  ]
});
const changeShow = (e: number[]) => {
  controlsShow.data.forEach((ele) => {
    if (e.indexOf(ele.value) === -1) {
      ele.show = false;
    } else {
      ele.show = true;
    }
  });
};
// 获取列表数据
const getData = async () => {
  try {
    const data: any = await GetOrganizationList({ type: 1 });
    console.log(112, data);

    originTreeData.data = changeOriginTreeData(data[0])
      ? (changeOriginTreeData(data[0]) as any)
      : {};
    console.log(originTreeData.data, 'originTreeData.data');
  } catch (error: unknown) {
    console.log(error);
  }
};
// 处理初始化数据
const changeOriginTreeData = (data: any, level = 1): any | null => {
  if (!data) return null;
  const { ctlValue, children, id } = data;
  const newData: any & {
    controlType?: any;
    percentage?: any;
    warning?: any;
    headcount?: any;
  } = {
    btnShow: false,
    userShow: false,
    children: children ? ([] as any) : (void 0 as any)
  };
  newData.position = data.positionName;
  newData.userId = data.responsibleId;
  newData.personnel = data.personnel;
  newData.authorized = data.authorized;
  newData.position = data.position;
  newData.node = data.node;
  newData.id = id;
  newData.positionShow = controlsShow.data[0];
  newData.employeeShow = controlsShow.data[1];
  newData.establishmentShow = controlsShow.data[2];
  newData.avatarShow = controlsShow.data[3];
  newData.topPositionShow = controlsShow.data[4];
  newData.rankShow = controlsShow.data[5];
  newData.contactInformationShow = controlsShow.data[6];
  newData.layout = true;
  newData.level = level;
  newData.controlType = data.controlType;
  newData.percentage = data.percentage;
  newData.warning = data.warning;
  newData.headcount = data.headcount;
  ctlValue.forEach((ele: any) => {
    // 组织名称
    if (ele.ctlCode === 'C30BBF36A5AF541F7A2657671DEE2EDD6') {
      newData.department = ele.ctlValue;
    }
    // 编制人数
    if (ele.ctlCode === 'CD25749DBA68E4BF3BCA616DD63751CB7') {
      newData.establishmentNum = ele.ctlValue;
    }
    // 组织负责人
    if (ele.ctlCode === 'CB0C63F38283045F58FFF1B1EABE5D151') {
      newData.name = ele.ctlValue;
    }
  });
  if (children && newData.children) {
    children.forEach((ele: any) => {
      const item = changeOriginTreeData(ele, level + 1);
      if (item) {
        newData.children?.push(item);
      }
    });
  }
  newData.name = data.responserName;
  return newData;
};
getData();
// 生成快照按钮
const snap = async () => {
  try {
    const { content } = await GetSnapShotList({
      pageNumber: 0,
      pageSize: 20
    });
    // 最近一次生成快照时间
    let lastTime =
      content.length > 0
        ? dayjs(dayjs(content[0]?.createdAt).format('YYYY-MM-DD'))
        : undefined;
    if (lastTime) {
      const currTime = dayjs().format('YYYY-MM-DD'); // 现在时间

      // 比较上一次生成的时间和当前时间如果大于1天则弹出弹框
      const diffInMilliseconds = Math.abs(lastTime.diff(currTime));
      const oneDayInMilliseconds = 24 * 60 * 60 * 1000;
      if (diffInMilliseconds >= oneDayInMilliseconds) {
        snapVisible.value = true;
      } else {
        Message.error('快照一天只能生成一次，请明天再试！');
        return;
      }
    } else {
      snapVisible.value = true;
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 生成快照弹出框自定义事件
const snapshotEmit = async () => {
  try {
    await PostSnap({
      id: userId
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 点击查看历史快照还是变更历史
const extraClick = (key: number) => {
  if (key === 1)
    router.push({
      name: 'HistoricalSnapshot',
      query: {
        tab: '2'
      }
    });
  else
    router.push({
      name: 'ChangeRecord'
    });
};

const clickTreeData = reactive({ data: null });
const clickTree = (e: any) => {
  clickTreeData.data = e;
};

const changeSize = (type: number) => {
  if (type === 1) {
    chart.value.enlarge();
  } else {
    chart.value.shrink();
  }
};

onMounted(() => {
  // 监听键盘ctrl+alt + 鼠标滚轮控制放大缩小事件
  document.addEventListener('wheel', function (event) {
    zoomWithMouse(event, chart.value.enlarge, chart.value.shrink);
  });

  // 监听键盘ctrl+alt + 键盘+ - 号控制放大缩小事件
  document.addEventListener('keydown', function (event) {
    zoomWithPlusAndMinus(event, chart.value.enlarge, chart.value.shrink);
  });
});
</script>

<style lang="less" scoped>
.wrap {
  display: flex;
}
.icons {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #4a86ff;
  margin-right: 5px;
  div,
  button {
    margin-right: 10px;
  }
  div:nth-child(4) {
    margin-right: 0px;
  }
  .icon {
    cursor: pointer;
    padding: 5px 5px 0 5px;
    border: 1px solid #4a86ff;
  }
}
p {
  padding: 0;
  margin: 0;
}
.main {
  // width: 1440px;
  height: 622px;
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
  .top {
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-content: center;
    .left {
      min-width: 350px;
      display: flex;
      align-content: center;
    }
  }
}
</style>
